/*
 *   Copyright (c) 2010 Sonrisa Informatikai Kft. All Rights Reserved.
 * 
 *  This software is the confidential and proprietary information of
 *  Sonrisa Informatikai Kft. ("Confidential Information").
 *  You shall not disclose such Confidential Information and shall use it only in
 *  accordance with the terms of the license agreement you entered into
 *  with Sonrisa.
 * 
 *  SONRISA MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
 *  THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 *  TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 *  PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SONRISA SHALL NOT BE LIABLE FOR
 *  ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 *  DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

package com.zh.jbet.web.panels.teammatch;

import com.zh.jbet.core.entity.Game;
import com.zh.jbet.core.tournament.entity.MatchResult;
import com.zh.jbet.core.tournament.entity.TeamMatch;
import com.zh.jbet.web.JBetServiceProvider;
import com.zh.jbet.web.components.ModalEditPanel;
import com.zh.jbet.web.model.EntityListModel;
import com.zh.jbet.web.model.IServiceableModel;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.datetime.markup.html.form.DateTextField;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.extensions.yui.calendar.DatePicker;
import org.apache.wicket.extensions.yui.calendar.DateTimeField;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.HiddenField;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.model.util.ListModel;

/**
 *
 * @author sonrisa
 */
public class TeamMatchEditModalPanel extends ModalEditPanel<TeamMatch> {
    public static final IChoiceRenderer<Game> GAME_CHOICE_RENDERER = new ChoiceRenderer<Game>("name");
    private static final String[] RESULT_KEYS = new String[] {"result.simpleTime", "result.extraTime", "result.penalty"};
    private static final String ERROR_BEFOREWIN = "error.match.beforeWin";

    private ListModel<MatchResult> editedResults;

    public TeamMatchEditModalPanel(final ModalWindow modal, IServiceableModel<TeamMatch> model) {
        super(modal, model);
        DateTimeField dtf;
        form.add(dtf = new DateTimeField("startTime"));
        //form.add(DateTextField.forShortStyle("startTime").add(new DatePicker()));
        EntityListModel teamList = new EntityListModel(JBetServiceProvider.TEAM_SERVICE);
        form.add(new DropDownChoice("home", teamList, GAME_CHOICE_RENDERER));
        form.add(new DropDownChoice("away", teamList, GAME_CHOICE_RENDERER));
        form.add(new HiddenField("parentId"));
        form.add(new HiddenField("rootId"));
        final WebMarkupContainer resultCont = new WebMarkupContainer("resultCont");
        resultCont.setOutputMarkupId(true);
        editedResults = new ListModel<MatchResult>(model.getObject().getResults());
        resultCont.add(new ListView<MatchResult>("results", editedResults) {
            @Override
            protected void populateItem(final ListItem<MatchResult> item) {
                String key = RESULT_KEYS[item.getIndex()];
                item.add(new Label("rtype", new StringResourceModel(key, null, key)));
                item.add(new RequiredTextField("homeGoalNo", new PropertyModel(item.getModel(), "homeGoalNo")));
                item.add(new RequiredTextField("awayGoalNo", new PropertyModel(item.getModel(), "awayGoalNo")));
                item.add(new AjaxLink("removeResult") {
                    @Override
                    public void onClick(AjaxRequestTarget target) {
                        editedResults.getObject().remove(item.getIndex());
                        target.addComponent(resultCont);
                    }
                });
            }
        });
        resultCont.add(new AjaxLink("addResult") {
            @Override
            public void onClick(AjaxRequestTarget target) {
                editedResults.getObject().add(new MatchResult());
                target.addComponent(resultCont);
            }

            @Override
            public boolean isVisible() {
                return editedResults.getObject().size() < RESULT_KEYS.length;
            }
        });
        form.add(resultCont);
    }

    protected boolean checkResults(AjaxRequestTarget target) {
        int idx = 0;
        for (MatchResult r: editedResults.getObject()) {
            if ((r.isAwayWin() || r.isHomeWin()) && (idx != editedResults.getObject().size()-1)) {
                error(getString(ERROR_BEFOREWIN, null, ERROR_BEFOREWIN));
                target.addComponent(feedback);
                return false;
            }
            idx++;
        }
        return true;
    }
    @Override
    protected boolean onModalSave(AjaxRequestTarget target) {
        if (checkResults(target)) {
            IServiceableModel<TeamMatch> mm = getServicableModel();
            int idx = 0;
            for (MatchResult r: editedResults.getObject()) {
                r.setGame(mm.getObject());
                r.setTypeIdx(idx++);
            }
            mm.getObject().setResults(editedResults.getObject());
            return super.onModalSave(target);
        } else {
            return false;
        }
    }


}

